package com.example.springbootmodel.Utils;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringJoiner;

/**
 * @program: springbootmodel
 * @description: cmd执行工具
 * @author: yang
 * @version: 1.0
 * @create: 2020/11/26 17:11
 **/
public class RuntimeUtil {

    /**
     * 执行Cmd命令
     * @param cmdStr 执行命令
     * @param dataFileDirPath 程序存放路径(不需要执行程序时为空)
     * @return
     */
    public static boolean excuteCmd(String cmdStr, String dataFileDirPath) {
        System.out.println(cmdStr + "---" + dataFileDirPath);
        try {
            // 执行命令
            Process process = null;
            if(dataFileDirPath == null) {
                process = Runtime.getRuntime().exec(cmdStr);
            }else {
                process = Runtime.getRuntime().exec(cmdStr, null, new File(dataFileDirPath));
            }
            outData(process);
            // 执行结果（0成功，其余都失败）
            int status = process.waitFor();
            return 0 == status;
        } catch (Exception e) {
            System.out.println("执行Cmd命令失败" + e);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 执行Cmd命令
     * @param cmdArr 执行命令数组
     * @return
     */
    public static Integer excuteCmd(String[] cmdArr) {
        System.out.println(StringUtils.join(cmdArr," "));
        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec(cmdArr);
            outData(process);
            return process.waitFor();
        } catch (Exception e) {
            System.out.println("执行Cmd命令失败" + e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 输出文件信息
     * */
    public static void outData(Process process) throws Exception{
        // 输出信息（try(){}会自动关闭()里的流）
        try(InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));){
            String line = br.readLine();
            while (line != null) {
                System.out.println(line);
                line = br.readLine();
            }
        }
        // 输出错误信息
        try(InputStream err = process.getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(err, "GBK"));){
            String line = br.readLine();
            while (line != null) {
                System.out.println(line);
                line = br.readLine();
            }
        }
        // 输入信息
        /*try(OutputStream out = process.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out,"GBK"))){

        }*/
    }

}
